<template>
    <div>
         <!-- 面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图-->
        <el-card>
            <el-alert show-icon :closable="false" title="注意：只允许为第三级分类设置参数"
            type="warning"></el-alert>
            <!--选择商品分类区域-->
            <el-row class="goods_cate">
                <el-col>
                    <span>选择商品分类:</span>
                    <!--级联分类选择框-->
                    <el-cascader v-model="selectCate" :options="catelist"
                    :props="cateProps" @change="cateSelectedChange"></el-cascader>
                </el-col>
            </el-row>
            <!--tab页签-->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button :disabled="isDisable" type="primary" size="mini" @click="addFormDialogVisible = true">添加参数</el-button>
                     <!--动态参数表格-->
                    <el-table :data="manyTabData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                                @close="handleClose(i, scope.row)">{{item}}</el-tag>
                                <!--添加属性-->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="warning" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button :disabled="isDisable" type="primary" size="mini" @click="addFormDialogVisible = true">添加属性</el-button>
                    <!--静态属性表格-->
                    <el-table :data="onlyTabData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                                @close="handleClose(i, scope.row)">{{item}}</el-tag>
                                <!--添加属性-->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="warning" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <!--添加参数对话框-->
            <el-dialog :title=" '添加' + titleText" :visible.sync="addFormDialogVisible" width="50%"
            @close="addFormClose">
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                    <el-form-item :label="titleText" prop="attr_name">
                        <el-input v-model="addForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addFormDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addParams">确 定</el-button>
                </span>
            </el-dialog>
            <!--修改参数对话框-->
            <el-dialog :title=" '修改' + titleText" :visible.sync="editFormDialogVisible" width="50%"
            @close="addFormClose">
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                    <el-form-item :label="titleText" prop="attr_name">
                        <el-input v-model="editForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editFormDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editParams">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
export default {
    data () {
        return {
            // 商品分类列表
            catelist: [],
            // 级联选择框配置对象
            cateProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: 'hover'
            },
            selectCate: [],
             // 查询条件
            queryInfo: {
                type: 3,
                pagenum: 1,
                pagesize: 5
            },
            // 被激活的页签名称
            activeName: 'many',
            // 动态参数数据
            manyTabData: [],
            // 静态属性数据
            onlyTabData: [],
            // 添加参数对话框
            addFormDialogVisible: false,
            // 添加表单对象
            addForm: {
                attr_name: ''
            },
            // 表单验证对象
            addFormRules: {
                attr_name: [
                    { required: true, message: '请输入添加内容', trigger: 'blur' }
                ]
            },
            // 修改参数对话框
            editFormDialogVisible: false,
            // 编辑表单对象
            editForm: {},
            // 编辑表单验证对象
            editFormRules: {
                attr_name: [
                    { required: true, message: '请输入修改内容', trigger: 'blur' }
                ]
            }
        }
    },
    created () {
        this.getCateList()
    },
    methods: {
        // 获取所有商品分类列表
        async getCateList () {
        const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
        if (res.meta.status !== 200) {
            return this.$message.error('获取商品分类失败')
        }
        this.catelist = res.data.result
        },
        // 级联选择框变化事件
        cateSelectedChange () {
            this.getParamsData()
        },
        // tab页签点击事件
        handleTabClick () {
            // console.log(this.activeName)
            this.getParamsData()
        },
        // 获取参数列表数据
        async getParamsData () {
            // console.log(this.selectCate)
            // 如果选中不是三级的分类
            if (this.selectCate.length !== 3) {
                this.selectCate = []
                // 清空对应表格数据
                this.manyTabData = []
                this.onlyTabData = []
                return
            }
            // 根据选择获取对应数据
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
            { params: { sel: this.activeName } })
            if (res.meta.status !== 200) {
                this.$message.error('获取失败')
            }
            // console.log(res)
             res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                // 添加文本框的显示状态
                item.inputVisible = false
                // 输入文本框的值
                item.inputVisible = ''
                })
            // 根据tab栏判断数据并分别保存
            if (this.activeName === 'many') {
                this.manyTabData = res.data
            } else {
                this.onlyTabData = res.data
            }
        },
        // 监听对话框关闭事件
        addFormClose () {
            this.$refs.addFormRef.resetFields()
        },
        // 添加参数
        addParams () {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.addForm.attr_name,
                    attr_sel: this.activeName
                })
                if (res.meta.status !== 201) {
                    return this.$message.error('添加失败')
                }
                this.$message.success('添加成功')
                this.addFormDialogVisible = false
                this.getParamsData()
            })
        },
        // 编辑对话框点击触发
        async showEditDialog (id) {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
                attr_sel: this.$activeName
            })
            if (res.meta.status !== 200) return
            this.editForm = res.data
            this.editFormDialogVisible = true
        },
        // 监听对话框关闭事件
        editFormClose () {
            this.$refs.editFormRef.resetFields()
        },
        // 修改参数
        editParams () {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
                    attr_name: this.editForm.attr_name,
                    attr_sel: this.activeName
                })
                console.log(res)
                if (res.meta.status !== 200) return this.$message.error('修改失败')
                this.$message.success('修改成功')
                this.getParamsData()
                this.editFormDialogVisible = false
            })
        },
        // 离开焦点 和 摁下enter 键触发事件
        handleInputConfirm (row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            // 如果没有return，则证明输入了内容，需要做后续处理
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false
            this.saveAttrvalue(row)
        },
        // 文本框显示
        showInput (row) {
            row.inputVisible = true
            // 文本框自动获取焦点
            // $nextTick 方法的作用，就是当页面被重新渲染之后，才会指定回调函数中的代码
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        // 删除属性事件
        handleClose (i, row) {
            row.attr_vals.splice(i, 1)
            this.saveAttrvalue(row)
        },
        // 发起请求保存属性
        async saveAttrvalue (row) {
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            if (res.meta.status !== 200) return this.$message.error('更新失败')
            this.$message.success('更新成功')
        }
    },
    computed: {
        // 如果按钮需要被禁用，返回true
        isDisable () {
            if (this.selectCate.length === 3) {
                return false
            }
            return true
        },
        // 当前选择三级分类id
        cateId () {
            if (this.selectCate.length === 3) {
                return this.selectCate[2]
            }
            return null
        },
        // 动态计算标题的文本
        titleText () {
            if (this.activeName === 'many') {
                return '动态参数'
            }
            return '静态属性'
        }
    }
}
</script>

<style lange="less" scope>
    .goods_cate {
        margin-top: 15px
    }
    .el-tag {
        margin: 8px;
    }
    .input-new-tag {
        width: 120px!important;
    }
</style>
